package com.qingcloud.adminbackend.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qingcloud.adminbackend.entity.sysorg.SysOrg;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 客户工具类
 *
 * @author luozehua
 */
public class OrgUtil {

    /**
     * 客户树
     *
     * @param sysOrgs
     * @param jsonObject
     * @param prentId
     * @return
     */
    public static JSONArray combainMenuJson(List<SysOrg> sysOrgs, JSONObject jsonObject, String prentId) {
        for (SysOrg sysOrg : sysOrgs) {
            String name = sysOrg.getName();
            String id = sysOrg.getId();
            String pId = sysOrg.getParentId();
            if (prentId.equals(pId)) {
                JSONArray children = jsonObject.getJSONArray("children");
                if (children == null) {
                    children = new JSONArray();
                    jsonObject.put("children", children);
                }
                JSONObject json = new JSONObject();
                json.put("label", name);
                json.put("value", id);
                json.put("children", new JSONArray());
                children.add(json);
                combainMenuJson(sysOrgs, json, id);
            }
        }
        return jsonObject.getJSONArray("children");
    }

    /**
     * 获取客户树，其中包含没有父节点权限但是有子节点权限的情况
     *
     * @param allManageOrgByUser
     * @return
     */
    public static List<SysOrg> getOrgTree(List<SysOrg> allManageOrgByUser) {
        List<SysOrg> parent = new ArrayList<>();
        List<SysOrg> sub = new ArrayList<>();
        //组装数据
        allManageOrgByUser.forEach(org -> {
            String parentId = org.getParentId();
            if (StringUtils.isEmpty(parentId)) {
                //父节点
                parent.add(org);
            } else {
                sub.add(org);
            }
        });
        parent.forEach(p -> {
            List<SysOrg> mySub = new ArrayList<>();
            String id = p.getId();
            for (int i = 0; i < sub.size(); i++) {
                String parentId = sub.get(i).getParentId();
                if (parentId.equals(id)) {
                    mySub.add(sub.get(i));
                }
            }
            p.setChildSysOrgs(mySub);
        });
        if (parent.isEmpty()) {
            return sub;
        } else {
            return parent;
        }
    }
}
